import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicInteger;

import com.sun.sgs.client.ClientChannel;
import com.sun.sgs.client.ClientChannelListener;

/**
 * A simple channel listener to be used with the Darkstar Server
 * 
 */
public class DarkstarChannelListener implements ClientChannelListener {
	/** records the number of channels joined when the client joins the channel */
	private final int channelNumber;
	/** sequence generator for counting channels. */
	private final AtomicInteger channelNumberSequence = new AtomicInteger(1);

	private static final String MESSAGE_CHARSET = "UTF-8";

	/**
	 * Inherited from ClientChannelListener. Uses channelNumber to keep a record
	 * of the number of channels joined
	 * 
	 * 
	 * Note that the listener will be given the channel on its callback methods,
	 * so it does not need to record the channel as state during the join.
	 */
	public DarkstarChannelListener() {
		channelNumber = channelNumberSequence.getAndIncrement();
	}

	/**
	 * Inherited from ClientChannelListener. Displays a message when the user
	 * agent leaves the channel.
	 */
	public void leftChannel(ClientChannel channel) {
		System.out.println("Removed from channel " + channel.getName());
	}

	/**
	 * Inherited from ClientChannelListener. Displays a message when the user
	 * agent leaves the channel.
	 */
	public void receivedMessage(ClientChannel channel, ByteBuffer message) {
		String decodedMessage = decodeString(message); // decode the string
		// darkstarBridge.sendToAgent(decodedMessage);//TODO // pass decoded
		// string to the relayMessage method
		System.out.println("DS Server channel sent: " + decodedMessage);
		System.out.println("[" + channel.getName() + "/ " + channelNumber
				+ "] " + decodedMessage);
	}

	public String decodeString(ByteBuffer buffer) {
		try {
			byte[] bytes = new byte[buffer.remaining()];
			buffer.get(bytes);
			return new String(bytes, MESSAGE_CHARSET);
		} catch (UnsupportedEncodingException e) {
			throw new Error("Character set " + MESSAGE_CHARSET + " not found",e);
		}
	}

}